package com.devunion.salon.persistence.dao;

import com.devunion.salon.persistence.Customer;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Viktar Liaskovich
 */
public class CustomerDao extends BaseDaoObject<Customer> {
    public Customer getByKey(Serializable key) {
        return (Customer) getHibernateTemplate().get(Customer.class, key);
    }

    public List<Customer> loadAll() {
        return getHibernateTemplate().loadAll(Customer.class);
    }

    public Set<Customer> getCustomerByCriteria(final String value, final int type) {
        return (Set<Customer>) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Criteria criteria = session.createCriteria(Customer.class);

                switch (type) {
                    case 1:
                        criteria.add(Restrictions.like("firstName", "%"+value+"%"));
                        break;
                    case 2:
                        criteria.add(Restrictions.like("lastName", "%"+value+"%"));
                        break;
                    case 3:
                        criteria.add(Restrictions.like("email", "%"+value+"%"));
                        break;
                    case 4:
                        criteria.add(Restrictions.like("phone", "%"+value+"%"));
                        break;
                    case 5:
                        criteria.add(Restrictions.like("cellPhone", "%"+value+"%"));
                        break;
                }

                List<Customer> result = criteria.list();
                return result == null || result.isEmpty() ? new HashSet<Customer>() : new HashSet<Customer>(result);
            }
        });
    }
}